import { setRouterComponent } from "libs/setRouterComponent";
import { cloneDeep } from "lodash";
import { frameInRoutes } from "@/router/routes";
import { resetRouter } from "@/router";

const PAGE_404 = {
  componentPath: "default/error/404",
  path: "*",
  name: "404",
  hidden: true,
};

export default {
  namespaced: true,
  state: {
    // 路由列表
    routerList: [],
  },
  actions: {
    /**
     * 设置路由列表
     */
    async set({ state, dispatch }, routerList) {
      // store 赋值
      state.routerList = [...routerList, PAGE_404];

      // 持久化
      await dispatch(
        "d2admin/db/set",
        {
          // dbName: "sys",
          path: "router.routerList",
          value: state.routerList,
          // user: true,
        },
        { root: true }
      );
    },
    /**
     * 初始化路由列表
     */
    async load({ state, dispatch, commit }, router) {
      // store 赋值
      let routerList = await dispatch(
        "d2admin/db/get",
        {
          // dbName: "sys",
          path: "router.routerList",
          defaultValue: [],
          // user: true,
        },
        { root: true }
      );

      // 特殊情况，添加上404页面
      if (!routerList.length) {
        routerList = [PAGE_404];
      }

      state.routerList = routerList;

      const formatedRouter = setRouterComponent(cloneDeep(routerList));

      // 处理路由 得到每一级的路由设置
      commit("d2admin/page/init", [...frameInRoutes, ...formatedRouter], {
        root: true,
      });

      resetRouter();

      // 动态添加路由
      router.addRoutes(formatedRouter);
    },
  },
};
